package com.lenovo.leos.filebrowser.ui;

import java.io.File;

import org.json.JSONException;

import android.app.Activity;
import android.app.Activity.OnTitleIconClickListener;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.leos.filebrowser.R;
import com.lenovo.leos.filebrowser.engine.util.DirDefines;
import com.lenovo.leos.filebrowser.netdisk.ErrorMessageDialog;
import com.lenovo.leos.filebrowser.netdisk.LenovoActivity;
import com.lenovo.leos.filebrowser.netdisk.NetDiskConstant;
import com.lenovo.leos.filebrowser.netdisk.NetDiskManager;
import com.lenovo.leos.filebrowser.netdisk.NetDiskOpResult;
import com.lenovo.leos.filebrowser.netdisk.NetFile;
import com.lenovo.leos.filebrowser.netdisk.ProgressMessageDialog;
import com.lenovo.leos.filebrowser.netdisk.NetDiskManager.OnNotifyListener;

public class TdActivity extends Activity implements OnClickListener,
		OnTouchListener, OnTitleIconClickListener {

	private static final String TAG = "TdActivity";

	private class LoginHandler extends Handler {
		public LoginHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "==> handleMessage");

			if (msg.what == MSG_LOGIN_OK) {
				ProgressMessageDialog.cancelDialog();
				Intent intent = new Intent();
				intent.setClass(
						TdActivity.this,
						com.lenovo.leos.filebrowser.netdisk.LenovoActivity.class);
				intent.putExtra("projectState", projectState);
				startActivity(intent);
				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				finish();
			} else if (msg.what == MSG_LOGIN_FAILED) {
				ProgressMessageDialog.cancelDialog();
				if (null != mndManager) {
					mndManager.unbindOpService();
					mndManager = null;
				}
				Toast.makeText(TdActivity.this, "login net disk failed",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	private class LoginThread extends Thread {

		Context mContext;
		boolean mStop = false;
		protected PowerManager.WakeLock mWakeLock;

		public LoginThread(Context context) {
			mContext = context;
			threadInt();
		}

		private void threadInt() {
			PowerManager powerManager = (PowerManager) mContext
					.getSystemService(Context.POWER_SERVICE);
			mWakeLock = powerManager.newWakeLock(
					PowerManager.SCREEN_DIM_WAKE_LOCK
							| PowerManager.ON_AFTER_RELEASE, TAG);
		}

		public void toStop() {
			mStop = true;
		}

		public void onLoginOk() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_OK, 0, 0, null);
			mHandler.sendMessage(msg);
		}

		public void onLoginFailed() {
			Message msg = mHandler.obtainMessage(MSG_LOGIN_FAILED, 0, 0, null);
			mHandler.sendMessage(msg);
		}
	}

	private static final boolean TAG_FLAG = true;
	private static String projectState;
	private TextView sdcardText;
	private boolean mRegisterReceiver = false;
	private LinearLayout phoneLayout, sdcardLayout, lenovoLayout;
	private String mUpload, mDownload;
	private static final String OPEN_SAVE = "android.intent.action.OPEN_SAVE_DIALOG";
	private static final int LENOVO_MODE_SAVE_FILE = 3;
	private static final int RAM_MODE_SELECT_PATH = 6;

	private static final int MSG_LOGIN_OK = 100000;
	private static final int MSG_LOGIN_FAILED = 100001;
	private String[] netFileIds, netFileNames;
	private boolean[] netFileTypes;
	private String uploadFileId;

	NetDiskManager mndManager = null;
	LoginHandler mHandler = new LoginHandler(Looper.myLooper());

	long mlCurOp = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "==> onCreate");

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_list);

		// mndManager.setEnableNotify(true);
		// mndManager.setOnOpNotifyListener(mntListener);

		projectState = getIntent().getStringExtra("projectState");
		mUpload = getIntent().getStringExtra("mUpload");
		mDownload = getIntent().getStringExtra("mDownload");
		netFileIds = getIntent().getStringArrayExtra("netFileIds");
		netFileNames = getIntent().getStringArrayExtra("netFileNames");
		netFileTypes = getIntent().getBooleanArrayExtra("netFileTypes");
		uploadFileId = getIntent().getStringExtra("uploadFileId");
		// if (null != netFileIds && null != netFileNames)
		if (TAG_FLAG) {
			// Log.d(TAG, "the netFileIds is ************** "
			// + netFileIds.length);
			// Log.d(TAG, "the netFileNames is *************** "
			// + netFileNames.length);
			Log.d(TAG, "the uploadFileId is =============== " + uploadFileId);
		}
		sdcardText = (TextView) findViewById(R.id.sdcardText);
		phoneLayout = (LinearLayout) findViewById(R.id.phoneLayout);
		sdcardLayout = (LinearLayout) findViewById(R.id.sdcardLayout);
		lenovoLayout = (LinearLayout) findViewById(R.id.lenovoLayout);
		phoneLayout.setOnTouchListener(this);
		sdcardLayout.setOnTouchListener(this);
		lenovoLayout.setOnTouchListener(this);
		phoneLayout.setOnClickListener(this);
		lenovoLayout.setOnClickListener(this);
		String status = Environment.getExternalStorageState();
		IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		commandFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
		commandFilter.addAction(Intent.ACTION_MEDIA_SHARED);
		commandFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
		commandFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
		commandFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
		commandFilter.addAction(Intent.ACTION_MEDIA_NOFS);
		commandFilter.addDataScheme("file");
		registerReceiver(SdCardIntentReceiver, commandFilter);
		mRegisterReceiver = true;
		if (status.equals(Environment.MEDIA_SHARED)
				|| status.equals(Environment.MEDIA_UNMOUNTED)
				|| status.equals(Environment.MEDIA_CHECKING)) {
			sdcardText.setTextColor(android.graphics.Color.GRAY);
			sdcardLayout.setEnabled(false);
		} else {
			sdcardText.setTextColor(android.graphics.Color.WHITE);
			sdcardLayout.setEnabled(true);
			sdcardLayout.setOnClickListener(this);
		}
		if (projectState.equals(DirDefines.mDir1)) {
			sdcardLayout.setVisibility(View.VISIBLE);
		} else if (projectState.equals(DirDefines.mDir3)) {
			sdcardLayout.setVisibility(View.GONE);
		}
		if (mUpload != null || mDownload != null) {
			lenovoLayout.setVisibility(View.GONE);
		} else {
			lenovoLayout.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onTitleIconClick() {
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mRegisterReceiver) {
			unregisterReceiver(SdCardIntentReceiver);
			if (TAG_FLAG)
				Log.i(TAG, "*********OnDestroy unregisterReceiver *********");
		}
	}

	@Override
	public void onClick(View view) {
		Intent intent = new Intent();
		switch (view.getId()) {
		case R.id.phoneLayout:
			if (mUpload != null || mDownload != null) {
				if (DirDefines.DOWNLOAD.equals(mDownload)) {
					intent.setAction(OPEN_SAVE);
					intent.putExtra("projectState", DirDefines.mDir3);
					intent.putExtra("mDownload", mDownload);
					mDownload = DirDefines.DOWNLOAD;
					if (null != netFileIds && null != netFileNames) {
						intent.putExtra("netFileIds", netFileIds);
						intent.putExtra("netFileNames", netFileNames);
						intent.putExtra("netFileTypes", netFileTypes);
					}
					intent.putExtra("request_code", RAM_MODE_SELECT_PATH);
					startActivityForResult(intent, RAM_MODE_SELECT_PATH);
					finish();
				} else if (DirDefines.UPLOAD.equals(mUpload)) {
					intent.setAction(OPEN_SAVE);
					intent.putExtra("uploadFileId", uploadFileId);
					intent.putExtra("request_code", LENOVO_MODE_SAVE_FILE);
					intent.putExtra("FILE_FILTER",
							".jpg .doc .txt .ppt .xls .rmvb .mp3 .flv .apk .png .vcf");
					startActivityForResult(intent, LENOVO_MODE_SAVE_FILE);
					finish();
				}
			} else {
				intent.putExtra("projectState", projectState);
				intent.setClass(TdActivity.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.sdcardLayout:
			if (null != mUpload || null != mDownload) {
				if (DirDefines.DOWNLOAD.equals(mDownload)) {
					intent.setAction(OPEN_SAVE);
					intent.putExtra("projectState", DirDefines.mDir3);
					intent.putExtra("mDownload", mDownload);
					mDownload = DirDefines.DOWNLOAD;
					if (null != netFileIds && null != netFileNames) {
						intent.putExtra("netFileIds", netFileIds);
						intent.putExtra("netFileNames", netFileNames);
						intent.putExtra("netFileTypes", netFileTypes);
					}
					intent.putExtra("request_code", RAM_MODE_SELECT_PATH);
					startActivityForResult(intent, RAM_MODE_SELECT_PATH);
					finish();
				} else if (DirDefines.UPLOAD.equals(mUpload)) {
					intent.setAction(OPEN_SAVE);
					intent.putExtra("uploadFileId", uploadFileId);
					intent.putExtra("request_code", LENOVO_MODE_SAVE_FILE);
					intent.putExtra("FILE_FILTER",
							".jpg .doc .txt .ppt .xls .rmvb .mp3 .flv .apk .png .vcf");
					startActivityForResult(intent, LENOVO_MODE_SAVE_FILE);
					finish();
				}
			} else {
				intent.putExtra("projectState", projectState);
				intent.setClass(TdActivity.this,
						com.lenovo.leos.filebrowser.ui.FileBrowser.class);
				startActivity(intent);
				finish();
			}
			break;
		case R.id.lenovoLayout:
			NetDiskConstant.NET_DISK_ROOT = null;
			Log.d(TAG, "the NetDiskConstant.NET_DISK_ROOT is =============== "+ NetDiskConstant.NET_DISK_ROOT);
			
			if (null == NetDiskConstant.NET_DISK_ROOT) {
				Log.i(TAG, "net disk is null");

				ProgressMessageDialog.showMessageDialog(this,
						getString(R.string.login), getString(R.string.loading));
				//dtdt
				
					if(mndManager == null){
						mndManager = NetDiskManager.getInstance(this);
						Log.i(TAG,"bind server ponit 3");
						mndManager.bindOpService();
					}
					
				
					//end
				
				LoginThread mThread = new LoginThread(this) {
					public void run() {
						Log.d(TAG, "@@@@@@@@@@@@@@@@@@@@");
						long id = -1;
						while (true) {
							Log.d(TAG, "#235235325#############");
							if (mndManager.isConnected()) {
								id = mndManager.login("xiexie_0101@163.com",
										"123456");
								Log.i(TAG,"login is true");
								break;  
							} else {  
								try {
									Thread.sleep(200);
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						}
						
						NetDiskOpResult result = null;

						do {
							try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							if(id != -1){
								result = mndManager.getResult(id);
							}

							if (null != result)
								break;
						} while (true);

						NetFile nfRoot = null;

						try {
							nfRoot = result.GetRootNetFile();
						} catch (JSONException e) {
							e.printStackTrace();
						}

						if (null != nfRoot) {
							NetDiskConstant.NET_DISK_ROOT = nfRoot;
							Log.e(TAG, "the root id is " + nfRoot.getID());
							onLoginOk();
						} else {
							mHandler.post(new Runnable() {
								 
								@Override
								public void run() {
									String errorMsg = NetDiskOpResult.strGetErrorMsg();
									if (TAG_FLAG) {
										Log.d(TAG, "the errorMsg is ================ "
												+ errorMsg);
										AlertDialog dialog = new AlertDialog.Builder(TdActivity.this)
										.setTitle(R.string.switching_directory)
										.setTitle(R.string.remind)
										.setMessage(errorMsg)
										.setPositiveButton(R.string.dlg_btn_ok,
												new DialogInterface.OnClickListener() {

													@Override
													public void onClick(DialogInterface dialog,
															int which) {
														dialog.cancel();
														ProgressMessageDialog.cancelDialog();
													}
												}).show();
									}
								}
							});
						}

					}
				};

				mThread.start();
			}
			else{
				Log.i(TAG, "net disk is not null 1111111" + NetDiskConstant.NET_DISK_ROOT);
				intent.setClass(
						TdActivity.this,
						com.lenovo.leos.filebrowser.netdisk.LenovoActivity.class);
				intent.putExtra("projectState", projectState);
				startActivity(intent);
				finish();
			}

			break;
		}
	}

	private BroadcastReceiver SdCardIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (TAG_FLAG)
				Log.d(TAG, "#################### SDaction = " + action);
			if (action.equals(Intent.ACTION_MEDIA_SHARED)
					|| action.equals(Intent.ACTION_MEDIA_UNMOUNTABLE)
					|| action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
					|| action.equals(Intent.ACTION_MEDIA_BAD_REMOVAL)
					|| action.equals(Intent.ACTION_MEDIA_NOFS)
					|| action.equals(Intent.ACTION_MEDIA_CHECKING)
					|| action.equals(Intent.ACTION_MEDIA_REMOVED)) {
				sdcardText.setTextColor(android.graphics.Color.GRAY);
				sdcardLayout.setEnabled(false);
			} else {
				sdcardText.setTextColor(android.graphics.Color.WHITE);
				sdcardLayout.setEnabled(true);
				sdcardLayout.setOnClickListener(TdActivity.this);
			}
		}
	};

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			phoneLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			sdcardLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
			lenovoLayout
					.setBackgroundResource(android.R.drawable.list_selector_background);
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		} else if (event.getAction() == MotionEvent.ACTION_CANCEL) {
			phoneLayout.setBackgroundColor(0);
			sdcardLayout.setBackgroundColor(0);
			lenovoLayout.setBackgroundColor(0);
		}
		return false;
	}
}
